import 'dart:io';

import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:jubobao/other/Widgets/JuBoCommonWidget.dart';
import 'package:jubobao/profile/addressBook/JuBoAddressBook.dart';
import 'package:jubobao/profile/addressBook/JuBpEmployeeModel.dart';
import 'package:multi_image_picker/multi_image_picker.dart';

class JuBoApprovalReport extends StatefulWidget {
  @override
  _JuBoApprovalReportState createState() => _JuBoApprovalReportState();
}

class _JuBoApprovalReportState extends State<JuBoApprovalReport> {
  Map<String, String> _map = {};

  List<Widget> _approvals = [];
  List<Widget> _chaosongs = [];

  List _images = [];
  String _error = 'No Error Dectected';

  String _date;
  bool _flag;
  File _image;
  final picker = ImagePicker();

  Future getImage() async {
    final pickedFile = await picker.getImage(source: ImageSource.gallery);
    setState(() {
      _image = File(pickedFile.path);
      _images.add(_image);
    });
  }

  Future<void> loadAssets() async {
    List<Asset> resultList = List<Asset>();
    String error = 'No Error Dectected';

    try {
      resultList = await MultiImagePicker.pickImages(
        maxImages: 300,
        enableCamera: true,
        selectedAssets: _images,
        cupertinoOptions: CupertinoOptions(takePhotoIcon: "chat"),
        materialOptions: MaterialOptions(
          actionBarColor: "#abcdef",
          actionBarTitle: "Example App",
          allViewTitle: "All Photos",
          useDetailsView: false,
          selectCircleStrokeColor: "#000000",
        ),
      );
    } on Exception catch (e) {
      error = e.toString();
    }

    if (!mounted) return;

    setState(() {
      _images = resultList;
      _error = error;
    });
  }

  Widget addWidget(f) {
    return InkWell(child: Padding(
      padding: const EdgeInsets.only(bottom: 30),
      child: Icon(Icons.add_circle, size: 60, color: Colors.black12,),
    ), onTap: f,);
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _flag = true;

    _approvals.add(addWidget(approvalPush));
    _chaosongs.add(addWidget(chaoSongPush));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('费用报销'),
        actions: <Widget>[
          IconButton(
              icon: Text(
                '保存',
              ),
              onPressed: () {
                print('保存按钮的点击事件');
                print(_map);
              }),
        ],
      ),
      body: SingleChildScrollView(
        child: Container(
          child: content(context),
          color: Colors.white30,
        ),
      ),
    );
  }

  Widget content(context) {
    return Column(
      children: <Widget>[
        contentTop(context),
        SizedBox(height: 8,),
        remark(),
        SizedBox(height: 8,),
        pic(),
        SizedBox(height: 8,),
        approval(),
        SizedBox(height: 8,),
        chaoSong(),
      ],
    );
  }

  Widget contentTop(context) {
    return Container(
      color: Colors.white,
      child: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          children: <Widget>[
            contentTopEditItem('报销类型', 'style'),
            contentTopEditItem('报销金额', 'money'),
            contentTopSelectTimeItem('使用日期', context, 'time'),
            contentTopEditItem('使用地点', 'address'),
            contentTopInvoiceItem('发票', 'invoice'),
          ],
        ),
      ),
    );
  }

  Widget contentTopEditItem(String title, String interface) {
    return Container(
      height: 44,
      child: Row(
        children: <Widget>[
          Text('$title:'),
          SizedBox(
            width: 8,
          ),
          Expanded(
              child: TextField(
                decoration: InputDecoration(
                  border: InputBorder.none,
                  hintText: '请输入${title}',
                ),
                onChanged: (value) {
                  print(value);
                  _map[interface] = value;
                },
//            style: TextStyle(fontSize: 14),
              )),
        ],
      ),
    );
  }

  Widget contentTopSelectTimeItem(String title, BuildContext context,
      String interface) {
    return InkWell(
      onTap: () {
        showDatePicker(
            context: context,
            initialDate: DateTime.now(),
            firstDate: DateTime.now().subtract(Duration(days: 30 * 12)),
            lastDate: DateTime.now().add(Duration(days: 30 * 12)),
            locale: Locale("zh"))
            .then((DateTime val) {
            setState(() {
              _date = '${val.year}-${val.month}-${val.day}';
              _map[interface] = _date;
            });
        });
      },
      child: Container(
        height: 44,
        child: Row(
          children: <Widget>[
            Text('$title:'),
            SizedBox(
              width: 8,
            ),
            Expanded(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: <Widget>[
                  Text(_date ?? '请选择'),
                  Icon(
                    Icons.arrow_forward_ios,
                    size: 12,
                  )
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

  Widget contentTopInvoiceItem(String title, invoice) {
    return Container(
      height: 44,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Text('$title:'),
          SizedBox(
            width: 8,
          ),
          Switch(
              value: _flag,
              onChanged: (value) {
                setState(() {
                  _flag = value;
                  _map[invoice] = value.toString();
                });
              })
        ],
      ),
    );
  }

  Widget remark() {
    return Container(
      color: Colors.white,
      child: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Text('备注说明'),
            TextField(
              keyboardType: TextInputType.multiline,
              maxLines: null,
              minLines: 3,
              decoration: InputDecoration(border: InputBorder.none),
              onChanged: (value) {
                _map['remark'] = value;
              },
            )
          ],
        ),
      ),
    );
  }

  Widget pic() {
    return Container(
      color: Colors.white,
      child: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Text('图片'),
                InkWell(
                  child: Icon(
                    Icons.photo_camera,
                    color: Colors.black54,
                  ),
                  onTap: getImage,
                )
              ],
            ),
            _images.length == 0
                ? Text('')
                : Container(
              child: GridView.builder(
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 4,
                ),
                itemBuilder: (ctx, index) {
                  return picItem(index);
                },
                itemCount: _images.length,
                shrinkWrap: true,
                physics: NeverScrollableScrollPhysics(),
              ),
            )
          ],
        ),
      ),
    );
  }

  Widget picItem(index) {
    return Padding(
        padding: const EdgeInsets.all(4.0),
        child: Stack(
          children: <Widget>[
            Image.file(
              _images[index],
              width: 100,
              fit: BoxFit.cover,
            ),
            Positioned(
              child: InkWell(
                child: Icon(
                  Icons.delete_forever,
                  color: Colors.red,
                ),
                onTap: () {
                  setState(() {
                    _images.removeAt(index);
                  });
                },
              ),
              right: 0,
              top: 0,
            )
          ],
        ));
  }

  Widget approval() {
    return Container(
      width: double.infinity,
      color: Colors.white,
      child: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Text('选择审批人'),
            Container(
              height: 100,
              child: ListView.builder(itemBuilder: (ctx, index) {
                return _approvals[index];
              },
                itemCount: _approvals.length,
                scrollDirection: Axis.horizontal,
                shrinkWrap: true,
              ),
            )

          ],
        ),
      ),
    );
  }

  Widget JuBoIconButton(ReList model, Function f) {
    return InkWell(
      child: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          children: <Widget>[
            Stack(
              children: <Widget>[
                ClipRRect(
                  child: Image.network(model.pic1, width: 50, height: 50,),
                  borderRadius: BorderRadius.circular(25),),
                Positioned(
                  right: -5, top: -5,
                  child: InkWell(
                    child: Icon(Icons.delete_forever, color: Colors.red,),
                    onTap: () {
                      setState(() {
                        _approvals.removeLast();
                        _approvals.add(addWidget(approvalPush));
                      });
                    },
                  ),
                )
              ],
            ),
            Text(model.linkMan)
          ],
        ),
      ),

      onTap: f,

    );
  }

  approvalPush() {
    Navigator.of(context).push(MaterialPageRoute(
        builder: (ctx) {
          return JuBoAddressBook();
        }
    )).then((model) {
//      _map['approval'] = model.id;
      setState(() {
        _approvals = [JuBoIconButton(model, approvalPush)];
      });
    });
  }

  chaoSongPush() {
    Navigator.of(context).push(MaterialPageRoute(
        builder: (ctx) {
          return JuBoAddressBook();
        }
    )).then((model) {
      setState(() {
        _chaosongs.insert(0, JuBoIconButton(model, chaoSongPush));
      });
    });
  }

  Widget chaoSong() {
    return Container(

      color: Colors.white,
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 8),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Text('添加抄送人'),
            Container(
              height: 100,
              child: ListView.builder(
                itemBuilder: (ctx, index) {
                  return _chaosongs[index];
                },
                itemCount: _chaosongs.length,
                scrollDirection: Axis.horizontal,
              ),
            )
          ],
        ),
      ),
    );
  }
}
